import React, { useState } from 'react'
import { useAuth } from '../contexts/AuthProvider'
import { OnboardingStep } from '../components/onboarding/OnboardingStep'
import { WelcomeStep } from '../components/onboarding/WelcomeStep'
import { InterestSelectionStep } from '../components/onboarding/InterestSelectionStep'
import { NotificationPreferencesStep } from '../components/onboarding/NotificationPreferencesStep'
import { CompletionStep } from '../components/onboarding/CompletionStep'
import { ArxivCategory, PaperPreferences, NotificationPreferences } from '../types/auth'

export function Onboarding() {
  const { updateProfile } = useAuth()
  const [currentStep, setCurrentStep] = useState(0)
  const [isCompleting, setIsCompleting] = useState(false)
  
  const [preferences, setPreferences] = useState<{
    categories: ArxivCategory[]
    keywords: string[]
    authors: string[]
    notifications: Partial<NotificationPreferences>
  }>({
    categories: [],
    keywords: [],
    authors: [],
    notifications: {
      email_notifications: true,
      weekly_digest: true,
      instant_alerts: false,
      paper_recommendations: true,
      digest_frequency: 'weekly'
    }
  })

  const steps = [
    { title: 'Welcome', component: 'welcome' },
    { title: 'Research Interests', component: 'interests' },
    { title: 'Notifications', component: 'notifications' },
    { title: 'Complete Setup', component: 'completion' }
  ]

  const handleNext = () => {
    if (currentStep < steps.length - 1) {
      setCurrentStep(currentStep + 1)
    }
  }

  const handlePrevious = () => {
    if (currentStep > 0) {
      setCurrentStep(currentStep - 1)
    }
  }

  const handleComplete = async () => {
    setIsCompleting(true)
    
    try {
      const paperPreferences: PaperPreferences = {
        categories: preferences.categories,
        keywords: preferences.keywords,
        authors: preferences.authors,
        institutions: [],
        max_results_per_search: 20,
        language_preferences: ['en']
      }

      const notificationPreferences: NotificationPreferences = {
        email_notifications: preferences.notifications.email_notifications || true,
        weekly_digest: preferences.notifications.weekly_digest || true,
        instant_alerts: preferences.notifications.instant_alerts || false,
        paper_recommendations: preferences.notifications.paper_recommendations || true,
        new_category_papers: true,
        author_updates: true,
        keyword_matches: true,
        push_notifications: false,
        sms_notifications: false,
        digest_frequency: preferences.notifications.digest_frequency || 'weekly',
        quiet_hours: {
          enabled: false,
          start_time: '22:00',
          end_time: '08:00'
        }
      }

      await updateProfile({
        paper_preferences: paperPreferences,
        notification_preferences: notificationPreferences,
        privacy_settings: {
          profile_visibility: 'academic',
          search_history_retention: 365,
          data_sharing_consent: true,
          analytics_consent: true,
          marketing_consent: false,
          research_participation_consent: true,
          data_export_format: 'json'
        },
        account_settings: {
          two_factor_enabled: false,
          login_alerts: true,
          session_timeout: 30,
          password_strength_requirement: 'medium',
          allowed_login_methods: ['email', 'google', 'orcid']
        }
      })

      // Redirect to dashboard
      window.location.href = '/app/dashboard'
    } catch (error) {
      console.error('Error completing onboarding:', error)
      // Show error message to user
    } finally {
      setIsCompleting(false)
    }
  }

  const updatePreferences = (updates: Partial<typeof preferences>) => {
    setPreferences(prev => ({ ...prev, ...updates }))
  }

  const renderCurrentStep = () => {
    const step = steps[currentStep]
    
    switch (step.component) {
      case 'welcome':
        return <WelcomeStep onNext={handleNext} />
      
      case 'interests':
        return (
          <InterestSelectionStep
            categories={preferences.categories}
            keywords={preferences.keywords}
            authors={preferences.authors}
            onUpdate={updatePreferences}
            onNext={handleNext}
            onPrevious={handlePrevious}
          />
        )
      
      case 'notifications':
        return (
          <NotificationPreferencesStep
            preferences={preferences.notifications}
            onUpdate={(notifications) => updatePreferences({ notifications })}
            onNext={handleNext}
            onPrevious={handlePrevious}
          />
        )
      
      case 'completion':
        return (
          <CompletionStep
            preferences={preferences}
            onComplete={handleComplete}
            onPrevious={handlePrevious}
            isCompleting={isCompleting}
          />
        )
      
      default:
        return null
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50">
      <div className="container mx-auto px-4 py-8">
        {/* Progress indicator */}
        <div className="max-w-2xl mx-auto mb-8">
          <div className="flex items-center justify-between">
            {steps.map((step, index) => (
              <OnboardingStep
                key={index}
                title={step.title}
                isActive={index === currentStep}
                isCompleted={index < currentStep}
                stepNumber={index + 1}
              />
            ))}
          </div>
        </div>

        {/* Step content */}
        <div className="max-w-4xl mx-auto">
          {renderCurrentStep()}
        </div>
      </div>
    </div>
  )
}